package com.android.stockme.backend.fetcher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.android.stockme.backend.util.Tupple;


public class YahooHistoryManager implements IHistoryManager {


	
	private static final long HISTORY_LENGTH = 7;
	private static final long MUL_2_HISTORY_LENGTH_MILI = (2*HISTORY_LENGTH*24*60*60*1000);
	/**
	 * @uml.property  name="cache"
	 */
	private Map<String, Tupple<String,List<Tupple<String,Float> > >  > cache = null; //Map:Symbol--->(Tupple<HistoryCreatedDate,List<Tupple<Date,closeValue>>>)	
	

	
	public YahooHistoryManager()
	{
		this.cache = new HashMap<String, Tupple<String,List<Tupple<String,Float>>>>();
	}
	
	
	public List<Tupple<String,Float>> fetchHistory(String symbol) {

		if(null == cache) 
			cache = new HashMap<String, Tupple<String,List<Tupple<String,Float> > >  >();
		long nowMilis = System.currentTimeMillis();
		Date todaDate = new Date(nowMilis);
		SimpleDateFormat formatterToday = new SimpleDateFormat("dd+MMM+yyyy");
		String todayStr = formatterToday.format(todaDate);//Create Current date string
		
		if (this.cache.containsKey(symbol) && (todayStr.equals(this.cache.get(symbol).getT1())))
		{
			return this.cache.get(symbol).getT2();//if we have the history in cache
		}
		this.cache.remove(symbol);
		
		long xdaysAgoInMilis = nowMilis - MUL_2_HISTORY_LENGTH_MILI;//Reduce 2*HISTORY_LENGTH days in milliseconds
		Date date = new Date(xdaysAgoInMilis);
		String strStartDate = "&a="+date.getMonth()+"&b="+date.getDate()+"&c="+(date.getYear()+1900);
		String finalUrlStr = "http://table.finance.yahoo.com/table.csv?s="+symbol+strStartDate+"&g=d";//&s-symbol &a-start month(0-11) &b-start day &c-start year
		List<Tupple<String,Float>> historyList = getYahooStockHistory(finalUrlStr);
		
		if (historyList.size() != HISTORY_LENGTH)
			return null;
		
		
		this.cache.put(symbol, new Tupple<String,List<Tupple<String,Float> >>(todayStr , historyList));
		return historyList;
		
	}//fetchHistory


	private List<Tupple<String,Float> > getYahooStockHistory(String urlStr) {
	  
        List<Tupple<String,Float> > result = new LinkedList<Tupple<String,Float> >();

        try {
        	URL url = new URL(urlStr);//URL for the stock history from yahoo! Finance
        	
            //Set the timeouts for connection and read
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(1000);
            InetAddress.getAllByName("www.yahoo.com");//check if we have connection
            
            //establish connection
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String[] values = null;
            String str;
            if ((str = in.readLine()) != null) {
                values = str.split(",");//get rid of the first line containing columns headlines
            }

            if ((values == null) || values.length < 7) {
                return result;
            }
            
            for(int i=0 ; i < HISTORY_LENGTH ; i++)
            {
                if ((str = in.readLine()) != null) 
                {
                    values = str.split(",");
                }
                else
                { 
                	break;//shouldn't be here
                }
                result.add(new Tupple<String,Float>(values[0].trim(),  Float.valueOf(values[4].trim())));//values[0]=string "date",  values[4]=float "closing value"
            
            }//read HISTORY_LENGTH lines with dates and closing day values
            
            in.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (NumberFormatException ex){
        	ex.printStackTrace();
        }
        
        return result;
    }//getYahooStockHistory
    
    

	/**
	 * Getter of the property <tt>cache</tt>
	 * @return  Returns the cache.
	 * @uml.property  name="cache"
	 */
	public Map<String, Tupple<String,List<Tupple<String,Float>>>>  getCache() {
		
		return cache;
		
	}//getCache

	/**
	 * Setter of the property <tt>cache</tt>
	 * @param cache  The cache to set.
	 * @uml.property  name="cache"
	 */
	public void setCache(Map<String, Tupple<String,List<Tupple<String,Float>>>>  cache) {
		
		this.cache = cache;
		
	}//cache

	
	public void removeStockFromCache(String symbol) {
		
		this.cache.remove(symbol);
		
	}//removeStockFromCache

	
}//YahooHistoryManager class
